#include "musiclist.h"
#include<QMimeDatabase>
#include<QDebug>
#include<QSqlQuery>


MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &musicUrls)
{

    for(auto e:musicUrls){

        auto it=begin();

        for(;it!=end();it++){
            if(it->getMusicUrl()==e){
                break;
            }
        }

        if(it!=end()){
            continue;
        }

        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(e.toLocalFile());
        QString mime=mimeType.name();

        qDebug()<<e<<":"<<mime;

        if(mime=="audio/mpeg"||mime=="audio/flac"||mime=="audio/wav"){
            qDebug()<<e;
            Music music(e);
            musicList.push_back(music);
        }

    }
}

iterator MusicList::findMusicByMusicId(const QString &musicId)
{
    for(auto it=begin();it!=end();it++){
        if(it->getMusicId()==musicId)
            return it;
    }
    return end();
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

void MusicList::readFromDB()
{
    QSqlQuery query;
    query.prepare("select musicId,musicName,musicSinger,albumName,musicUrl,duration,isLike,isHistory from MusicInfo");
    if(!query.exec()){
        qDebug()<<"查询失败";
        return;
    }

    while(query.next()){
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbumn(query.value(3).toString());
        music.setMusicUrl(query.value(4).toString());
        music.setMusicDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        qDebug()<<music.getMusicUrl();

        musicList.push_back(music);

    }
}

void MusicList::writeToMusicDB()
{
    for(auto music:musicList){
        music.InsertMusicToDB();
    }
}

void MusicList::push_back(Music m)
{
    musicList.push_back(m);
}

